<?php
class ArchiveController extends BaseController {
	
	protected function _init_() {
		$this->setTitle(__('文章归档'));
	}
	
	public function indexAction($params = array()) {
		
		//显示年/月下的文章
		if ( $params['date'] ) {
			if ( !preg_match('/^[\d\-]+$/', $params['date']) ) {
				self::error();
			}
			list($year, $month, $day) = explode('-', $params['date']);
			
			$archives = array();
			
			$page = max(1, intval($params['page']));
			$pagesize = (int)config('pagesize') * 2;
			$offset = ( $page - 1 ) * $pagesize;
			$url = "mod=archives&date={$params['date']}&page={$page}";
			
			//年月日
			if ( $year && $month && $day ) {
				$wheresql = " yearmonth = '{$year}{$month}' AND `day` = '$day'";
			//年月
			} elseif ( $year && $month ) {
				$wheresql = " yearmonth = '{$year}{$month}'";
			//年
			} elseif ( $year ) {
				$wheresql = " yearmonth BETWEEN ".($year * 100)." AND ".(($year+1) * 100);
			} else {
				error_404();
			}
			
			$count = $db->count('calendar', $wheresql);
			
			if ( $count ) {
				
				$postids = array();
				$query = $db->query("SELECT postid FROM ".tname('calendar')." 
				WHERE $wheresql LIMIT $offset, $pagesize");
				while ( $row = $db->fetch_array($query) ) {
					$postids[] = $row['postid'];
				}
				
				if ( $postids ) {
					$query = $db->query("SELECT id,cateid,title,alias,dateline,views,comments FROM ".tname('post')." WHERE 
					id IN (".simplode($postids).") AND `status` = 1 ORDER BY dateline");
					while ( $row = $db->fetch_array($query) ) {
						$cate = $_CACHE['cate'][$row['cateid']];
						$row['url'] = url("mod=post&id={$row['id']}&alias={$row['alias']}");
						$row['category'] = sprintf('<a href="%1$s" title="%2$s">%2$s</a>', url('mod=cate&id='.$cate['id'].'&alias='.$cate['alias']), $cate['catename']);
						$row['posttime'] = get_date($row['dateline']);
						$archives[] = $row;
					}					
				}
				
			}
			
		//按年月归档
		} else {
			
			if ( !$archives = $cache->get('archives') ) {
				$archives = array();
				$query = $db->query("SELECT LEFT(yearmonth,4) AS year, RIGHT(yearmonth, 2) AS month, COUNT(*) AS num FROM ".tname('calendar')." GROUP BY yearmonth ORDER BY yearmonth ASC");
				while ( $row = $db->fetch_array($query) ) {
					$archives[$row['year']][$row['month']] = $row['num'];
				}
				$db->free_result($query);
				@ksort($archives);
				$cache->set('archives', $archives, $cachetime);
			}
			$archives = (array)$archives;
		}		
	}
}
